<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Drag</title>
    <link rel="stylesheet" href="../static/css/drag.css">
</head>
<script>
    window.onload = function () {
        const scroll = document.getElementById("scroll");
        const demo = document.getElementById("demo");
        const bar = scroll.children[0];
        const mask = scroll.children[1];
        bar.onmousedown = function (event) {
            event = event || window.event;
            // 获取事件触发源对象的偏移量
            const leftOff = event.clientX - this.offsetLeft;
            // 保存对象指针
            const _this = this;
            document.onmousemove = function (event) {
                // console.log(_this);
                event = event || window.event;
                _this.style.left = event.clientX - leftOff + "px";
                let value = parseInt(_this.style.left);
                if (value < 0) {
                    _this.style.left = 0 + "px";
                    value = 0;
                } else if (value > 390) {
                    _this.style.left = "390px";
                    value = 390;
                }
                // 拖动的距离就是进度条走得距离
                mask.style.width = _this.style.left;
                // 计算进度条百分比
                let offset = (value / 390) * 100
                demo.innerHTML = "进度条滑动" + Math.round(offset) + "%";
                // 避免鼠标拖拽时被选中
                window.getSelection()
                    ? window.getSelection().removeAllRanges()
                    : document.getSelection().removeAllRanges();
            };
            document.onmouseup = function () {
                document.onmousemove = null;
            };
        };
    };
</script>
<body>
<div class="scroll" id="scroll">
    <div class="bar"></div>
    <div class="mask"></div>
</div>
<div id="demo">进度条滑动0%</div>
</body>
</html>
